package com.app.studyroom;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.app.studyroom.adapter.BookingAdapter;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.messageNotice.MessageItem;
import com.app.studyroom.api.model.ssrBooking.BookingDeleteRequest;
import com.app.studyroom.api.model.ssrBooking.BookingItem;
import com.app.studyroom.api.model.ssrBooking.BookingPageRequest;
import com.app.studyroom.api.model.ssrBooking.BookingPageResponse;
import com.app.studyroom.api.model.ssrBooking.SelfStudyRequest;
import com.app.studyroom.api.model.ssrUser.StudyDurationItem;
import com.app.studyroom.api.model.ssrUser.UserIdRequest;
import com.app.studyroom.api.model.ssrUser.UserUpdateRequest;
import com.app.studyroom.db.UserInfo;
import com.app.studyroom.dialog.CustomSizeDialog;
import com.bumptech.glide.Glide;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;

import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.Okio;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PersonalCenterActivity extends BaseActivity {

    private TextView tvUserName, tvUserNumber, tvTotalStudy;
    private TextView tvUnreadBadge;
    private Button btnReserveSeat, btnChangePhone, btnLogout, btnChangePassword, btnPersonStudyReport, btnMessageNotice;
    private RecyclerView recyclerBooking;
    private BookingAdapter bookingAdapter;
    private List<BookingItem> bookingList = new ArrayList<>();
    private LineChart lineChart;
    private ImageView Image_back;
    private ImageView imgAvatar;
    private LinearLayout layout_hide , layout_hide_1;
    //定时刷新
    private final long REFRESH_INTERVAL_MS = 1 * 60 * 1000; // 1分钟
    private final android.os.Handler refreshHandler = new android.os.Handler();
    private final Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            loadUserBookings();
            updateUnreadBadge();
            refreshHandler.postDelayed(this, REFRESH_INTERVAL_MS);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_center);

        tvUserName = findViewById(R.id.tv_user_name);
        tvUserNumber = findViewById(R.id.tv_user_number);
        tvTotalStudy = findViewById(R.id.tv_total_study);
        tvUnreadBadge = findViewById(R.id.tvUnreadBadge);

        //tvBindSeatPlace = findViewById(R.id.tvBindSeatPlace);
        btnReserveSeat = findViewById(R.id.btn_reserve_seat);
        btnChangePhone = findViewById(R.id.btn_change_phone);
        btnChangePassword = findViewById(R.id.btn_change_password);
        btnLogout = findViewById(R.id.btn_logout);
        btnPersonStudyReport = findViewById(R.id.btn_person_study_report);
        btnMessageNotice = findViewById(R.id.btn_message_notice);

        lineChart = findViewById(R.id.line_chart_study);
        Image_back = findViewById(R.id.ic_back);
        imgAvatar = findViewById(R.id.img_avatar);

        //隐藏项
        layout_hide=findViewById(R.id.layout_hide);
        layout_hide.setVisibility(View.INVISIBLE);
        layout_hide_1=findViewById(R.id.layout_hide_1);
        layout_hide_1.setVisibility(View.INVISIBLE);

        // 预约列表
        recyclerBooking = findViewById(R.id.recycler_booking_list);
        bookingAdapter = new BookingAdapter(this, bookingList);
        recyclerBooking.setLayoutManager(new LinearLayoutManager(this));
        recyclerBooking.setAdapter(bookingAdapter);
        bookingAdapter.setOnCancelClickListener(item -> cancelBooking(item.getId()));

        SharedPreferences sessionSp = getSharedPreferences("Session", MODE_PRIVATE);
        String userName = sessionSp.getString("userName", "未登录用户");
        String userNumber = sessionSp.getString("userNumber", "未知学号");
        String imageId = sessionSp.getString("userImage","");
        String studyTime = sessionSp.getString("studyTime","学习时长未知");
//        String bindSeatPlace = sessionSp.getString("bindSeatPlace", null);
//        String bindSeatNum = sessionSp.getString("bindSeatNum", null);

        tvUserName.setText(userName);
        tvUserNumber.setText("学号：" + userNumber);
        tvTotalStudy.setText("累计学习时长：" + studyTime + " 小时");
        //绑定座位显示
//        String seatDisplay;
//        if (bindSeatPlace != null && !bindSeatPlace.trim().isEmpty() &&
//                bindSeatNum != null && !bindSeatNum.trim().isEmpty()) {
//            seatDisplay = bindSeatPlace + "-" + bindSeatNum;
//        } else {
//            seatDisplay = "无";
//        }
//        tvBindSeatPlace.setText(seatDisplay);

        btnPersonStudyReport.setOnClickListener(v -> generateStudyReport());
        btnMessageNotice.setOnClickListener(v -> {
            Intent intent = new Intent(PersonalCenterActivity.this, MessageNoticeActivity.class);
            startActivity(intent);
        });
        btnChangePhone.setOnClickListener(v -> showUpdatePhoneDialog());
        btnChangePassword.setOnClickListener(v -> showUpdatePasswordDialog());
        btnReserveSeat.setOnClickListener(v -> {
            Intent intent = new Intent(PersonalCenterActivity.this, ClassActivity.class);
            intent.putExtra("enableReservation", true); // ✅ 传递是否允许预约的标志
            startActivity(intent);
        });
        btnLogout.setOnClickListener(v -> {
            // 清除 SharedPreferences 中的登录状态
            SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.clear(); // ✅ 清空保存的 token 和用户信息
            editor.apply();

            // 跳转回首页
            Intent intent = new Intent(PersonalCenterActivity.this, HomeActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });
        Image_back.setOnClickListener(v -> onBackPressed());
        bookingAdapter.setOnStartStudyClickListener(item -> triggerSelfStudy(item.getId(), "start"));
        bookingAdapter.setOnEndStudyClickListener(item -> triggerSelfStudy(item.getId(), "end"));
        loadUserBookings();
        loadAvatarFromServer(imageId);
        loadStudyDurationChart();


    }
    @Override
    protected void onResume() {
        super.onResume();
        loadUserBookings();
        updateUnreadBadge();
        refreshHandler.postDelayed(refreshRunnable, REFRESH_INTERVAL_MS); // 启动定时刷新
    }
    @Override
    protected void onPause() {
        super.onPause();
        refreshHandler.removeCallbacks(refreshRunnable); // 防止内存泄露
    }
    private void loadUserBookings() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);
        long userId = sp.getLong("userId", -1L);

        if (token == null || userId == -1L) return;

        BookingPageRequest request = new BookingPageRequest(1, 10);
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.pageBookingList(token, request).enqueue(new Callback<BookingPageResponse>() {
            @Override
            public void onResponse(Call<BookingPageResponse> call, Response<BookingPageResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    bookingList.clear();
                    for (BookingItem item : response.body().getData().getData()) {
                        if (item.getBookingUser() == userId) {
                            bookingList.add(item);
                        }
                    }
                    bookingAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<BookingPageResponse> call, Throwable t) {
                Toast.makeText(PersonalCenterActivity.this, "加载预约失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void cancelBooking(long bookingId) {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);
        if (token == null) return;

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.deleteBooking(token, new BookingDeleteRequest(bookingId)).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Toast.makeText(PersonalCenterActivity.this, "取消成功", Toast.LENGTH_SHORT).show();
                    loadUserBookings();
                } else {
                    Toast.makeText(PersonalCenterActivity.this, "取消失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Toast.makeText(PersonalCenterActivity.this, "取消请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void triggerSelfStudy(long bookingId, String action) {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);
        if (token == null) {
            Toast.makeText(this, "未登录", Toast.LENGTH_SHORT).show();
            return;
        }

        SelfStudyRequest request = new SelfStudyRequest(String.valueOf(bookingId), action);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.startOrEndSelfStudy(token, request).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Toast.makeText(PersonalCenterActivity.this,
                            ("start".equals(action) ? "开始" : "结束") + "学习成功", Toast.LENGTH_SHORT).show();
                    loadUserBookings();
                    loadUserInfoById();
                } else {
                    Toast.makeText(PersonalCenterActivity.this,
                            "操作失败：" + (response.body() != null ? response.body().getMessage() : "未知错误"),
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Toast.makeText(PersonalCenterActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void loadAvatarFromServer(String imageId) {
        if (imageId == null || imageId.isEmpty()) return;

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Map<String, String> request = new java.util.HashMap<>();
        request.put("id", imageId);

        Call<ApiResponse<String>> call = apiService.getImageDetail(request);
        call.enqueue(new Callback<ApiResponse<String>>() {
            @Override
            public void onResponse(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    String imageUrl = response.body().getData();
                    Glide.with(PersonalCenterActivity.this)
                            .load(imageUrl)
                            .placeholder(R.drawable.bg_circle_avatar)
                            .into(imgAvatar);
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                Toast.makeText(PersonalCenterActivity.this, "加载头像失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void showUpdatePhoneDialog() {
        CustomSizeDialog dialog = new CustomSizeDialog(this, R.layout.dialog_change_phone, 0.388f, 0.3f);
        dialog.show();

        EditText editPhone = dialog.findViewById(R.id.edit_phone);
        Button btnConfirm = dialog.findViewById(R.id.btn_confirm);
        Button btnCancel = dialog.findViewById(R.id.btn_cancel);

        btnConfirm.setOnClickListener(v -> {
            String newPhone = editPhone.getText().toString().trim();
            if (newPhone.isEmpty()) {
                Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
            String token = sp.getString("token", null);
            long userId = sp.getLong("userId", 0);

            UserUpdateRequest request = new UserUpdateRequest();
            request.setId(userId);
            request.setUserSjh(newPhone);

            ApiService apiService = ApiClient.getClient().create(ApiService.class);
            apiService.userUpdate(token, request).enqueue(new Callback<ApiResponse<Object>>() {
                @Override
                public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        Toast.makeText(PersonalCenterActivity.this, "手机号更新成功", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    } else {
                        Toast.makeText(PersonalCenterActivity.this, "手机号更新失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                    Toast.makeText(PersonalCenterActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        });

        btnCancel.setOnClickListener(v -> dialog.dismiss());
    }
    private void showUpdatePasswordDialog() {
        CustomSizeDialog dialog = new CustomSizeDialog(this, R.layout.dialog_change_password, 0.388f, 0.3f);
        dialog.show();

        EditText editPassword1 = dialog.findViewById(R.id.edit_password_1);
        EditText editPassword2 = dialog.findViewById(R.id.edit_password_2);
        Button btnConfirm = dialog.findViewById(R.id.btn_confirm);
        Button btnCancel = dialog.findViewById(R.id.btn_cancel);

        btnConfirm.setOnClickListener(v -> {
            String pwd1 = editPassword1.getText().toString().trim();
            String pwd2 = editPassword2.getText().toString().trim();

            if (pwd1.isEmpty() || pwd2.isEmpty()) {
                Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!pwd1.equals(pwd2)) {
                Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                return;
            }

            SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
            String token = sp.getString("token", null);
            long userId = sp.getLong("userId", 0);

            UserUpdateRequest request = new UserUpdateRequest();
            request.setId(userId);
            request.setUserPassword(pwd1);

            ApiService apiService = ApiClient.getClient().create(ApiService.class);
            apiService.userUpdate(token, request).enqueue(new Callback<ApiResponse<Object>>() {
                @Override
                public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        Toast.makeText(PersonalCenterActivity.this, "密码更新成功", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    } else {
                        Toast.makeText(PersonalCenterActivity.this, "密码更新失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                    Toast.makeText(PersonalCenterActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        });

        btnCancel.setOnClickListener(v -> dialog.dismiss());
    }
    private void generateStudyReport() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);
        String userName = sp.getString("userName", "用户"); // 默认用户名

        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Log.d("StudyReport", "开始请求生成报告接口，Token: " + token);

        apiService.generateStudyReportRaw(token).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("StudyReport", "响应状态码: " + response.code());
                if (response.isSuccessful() && response.body() != null) {
                    try {
                        // 使用用户名构造文件名
                        String safeName = userName.replaceAll("[\\\\/:*?\"<>|]", "_");
                        File file = new File(getExternalFilesDir(null), safeName + "的学习报告.docx");
                        Log.d("StudyReport", "准备写入文件路径: " + file.getAbsolutePath());

                        BufferedSink sink = Okio.buffer(Okio.sink(file));
                        sink.writeAll(response.body().source());
                        sink.close();
                        Log.d("StudyReport", "文件保存成功");

                        Toast.makeText(PersonalCenterActivity.this,
                                "学习报告已保存至: " + file.getAbsolutePath(),
                                Toast.LENGTH_LONG).show();

                    } catch (Exception e) {
                        Log.e("StudyReport", "保存文件失败", e);
                        Toast.makeText(PersonalCenterActivity.this, "保存失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.e("StudyReport", "生成报告失败，状态码: " + response.code());
                    Toast.makeText(PersonalCenterActivity.this, "生成报告失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("StudyReport", "网络请求失败", t);
                Toast.makeText(PersonalCenterActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void updateUnreadBadge() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);
        if (token == null) return;

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getMessageList(token).enqueue(new Callback<ApiResponse<List<MessageItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<MessageItem>>> call, Response<ApiResponse<List<MessageItem>>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    List<MessageItem> list = response.body().getData();
                    long unreadCount = list.stream().filter(m -> m.getStatus() == 0).count();

                    if (unreadCount > 0) {
                        // ✅ 防止数字太大
                        if (unreadCount > 99) {
                            tvUnreadBadge.setText("99+");
                        } else {
                            tvUnreadBadge.setText(String.valueOf(unreadCount));
                        }
                        tvUnreadBadge.setVisibility(View.VISIBLE);
                    } else {
                        tvUnreadBadge.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<MessageItem>>> call, Throwable t) {
                Log.e("Badge", "加载未读数失败", t);
            }
        });
    }
    private void loadUserInfoById() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);
        long userId = sp.getLong("userId", -1L);
        if (token == null || userId == -1L) return;

        UserIdRequest request = new UserIdRequest(userId);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getUserById(request).enqueue(new Callback<ApiResponse<UserInfo>>() {
            @Override
            public void onResponse(Call<ApiResponse<UserInfo>> call, Response<ApiResponse<UserInfo>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    UserInfo user = response.body().getData();
                    if (user != null) {
                        // 更新页面显示内容
                        tvUserName.setText(user.getUserName());
                        tvUserNumber.setText("学号：" + user.getUserNumber());
                        tvTotalStudy.setText("累计学习时长：" + user.getStudyTime() + " 小时");
                        loadAvatarFromServer(user.getUserImage());
                    }
                } else {
                    Toast.makeText(PersonalCenterActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<UserInfo>> call, Throwable t) {
                Toast.makeText(PersonalCenterActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //学习图表
    private void loadStudyDurationChart() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);
        if (token == null) return;

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getUserStudyDurations(token).enqueue(new Callback<ApiResponse<List<StudyDurationItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<StudyDurationItem>>> call, Response<ApiResponse<List<StudyDurationItem>>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    List<StudyDurationItem> data = response.body().getData();
                    renderLineChart(data);
                } else {
                    Toast.makeText(PersonalCenterActivity.this, "加载学习时长失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<StudyDurationItem>>> call, Throwable t) {
                Toast.makeText(PersonalCenterActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void renderLineChart(List<StudyDurationItem> dataList) {
        LineChart chart = findViewById(R.id.line_chart_study);
        List<Entry> entries = new ArrayList<>();
        List<String> xLabels = new ArrayList<>();

        for (int i = 0; i < dataList.size(); i++) {
            StudyDurationItem item = dataList.get(i);
            entries.add(new Entry(i, item.getDuration()));
            xLabels.add(item.getDate().substring(5)); // 显示 MM-dd
        }

        LineDataSet dataSet = new LineDataSet(entries, "每日学习时长");

        dataSet.setColor(Color.RED);         // 红色线条
        dataSet.setLineWidth(3f);            // 线条粗一点
        dataSet.setCircleRadius(5f);         // 圆点半径
        dataSet.setCircleColor(Color.RED);   // 圆点颜色为红色

        LineData lineData = new LineData(dataSet);
        chart.setData(lineData);
        chart.getDescription().setEnabled(false);
        chart.getAxisRight().setEnabled(false);

        chart.setDrawGridBackground(false);
        chart.setDrawBorders(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setDrawGridLines(false);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int index = (int) value;
                return (index >= 0 && index < xLabels.size()) ? xLabels.get(index) : "";
            }
        });

        YAxis yAxis = chart.getAxisLeft();
        yAxis.setAxisMinimum(0f);
        yAxis.setDrawGridLines(false);

        chart.invalidate();
    }





}
